#include "socket.h"
#include "ui_socket.h"
#include <QDebug>
#include <QObject>
#include <QUdpSocket>


Socket::Socket(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Socket)
{
    ui->setupUi(this);
    udpSocket = new QUdpSocket(this);
    udpSocket->bind(QHostAddress::Any, 50053);
    connect(udpSocket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()));
    ui->lineEdit->setText("3516 UDP Test!!!!");
}

Socket::~Socket()
{
    delete ui;
    delete udpSocket;
}

void Socket::on_pushButton_released()
{
    QString sendbuf=ui->lineEdit->text();
    QString  IP="192.168.1.150";
    QString  port="5555";
    sendMsgToSever(sendbuf,IP,port);
}

void Socket::readPendingDatagrams()
{
    while (udpSocket->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());
        udpSocket->readDatagram(datagram.data(),datagram.size());
        qDebug()<<"data"<<datagram;
        ui->lineEdit_2->setText(datagram);
    }
}

void Socket::sendMsgToSever(const QString sMsg,const QString sHostAddr,const QString sHostPort)
{
    QByteArray baDada = sMsg.toLatin1();
    udpSocket->writeDatagram(baDada,QHostAddress(sHostAddr),sHostPort.toInt());
}


void Socket::on_pushButton_2_released()
{
      ui->lineEdit_2->clear();
}
